<link href="${rc.getContextPath()}/manage/css/dwzCustomCss/dwz.custom.css?v=${ver}" rel="stylesheet" type="text/css">
<style>
#treeTypePanel > div {height: 180px !important; overflow: auto; border: 1px solid #D9DFE5;}
</style>
<div id="inventoryAlarmRecipientInfo" class="pageContent uiComplete" style="overflow: hidden;">
    <form class="pageForm required-validate" >
        <div class="pageFormContent" >
            <input type="hidden" name="navTabId" value="${navTabId!''}">
            <input type="hidden" name="_userCode" value="${userCode}">
            <input type="hidden" name="_storageLocationCode" value="${storageLocationCode}">
            <input type="hidden" name="_materialCode" value="${materialCode}">
            <fieldset>
                <dl>
                    <dt>用户编号：</dt>
                    <dd>
                        <input name="userCode" value="${userCode}" 
                            size="22" type="text" maxlength="40" class="required  alphanumeric toUp"
                            <#if pattern == "add">
                            id="inventoryAlarmRecipientUserLookup.userCode"
                            postField="userCode" suggestFields="userCode,userText" 
                            suggestUrl="${rc.getContextPath()}/manage/user/userSuggest" lookupGroup="inventoryAlarmRecipientUserLookup"
                            remote="${rc.getContextPath()}/manage/user/checkedUserCodeNotExits"
                            warn="<@label key='userCode.C,doesNotExist.C'>用户编号不存在</@label>"
                            </#if>
                            <#if pattern!="add">
                            readonly="readonly"
                            </#if>
                        />
                    </dd>
                </dl>
                <dl>
                    <dt>用户名：</dt>
                    <dd>
                        <input name="userText" id="inventoryAlarmRecipientUserLookup.userText" value="${userText}"    size="22" type="text" maxlength="60" readonly="readonly" />
                    </dd>
                </dl>
                <dl>
                    <dt>库位编号：</dt>
                    <dd>
                        <input name="storageLocationCode"
                            value="${storageLocationCode!''}"
                            size="22" type="text" maxlength="60" 
                            <#if pattern == "add">
                            id="inventoryAlarmRecipientStorageLocationLookup.storageLocationCode"
                            postField="storageLocationCode" suggestFields="storageLocationCode" 
                            suggestUrl="${rc.getContextPath()}/manage/storageLocation/storageLocationSuggest" lookupGroup="inventoryAlarmRecipientStorageLocationLookup"
                            remote="${rc.getContextPath()}/manage/storageLocation/validateStorageLocation"
                            warn="<@label key='storageLocationCode.C,doesNotExist.C'>库位编号不存在</@label>"
                            </#if>
                            <#if pattern!="add">
                            readonly="readonly"
                            </#if>
                          />
                    </dd>
                </dl>
                <dl>
                    <dt>物料编号：</dt>
                    <dd>
                        <input name="materialCode"
                            value="${materialCode}"
                            size="22" type="text" maxlength="60" 
                            <#if pattern == "add">
                            id="inventoryAlarmRecipientMaterialLookup.materialCode"
                            postField="materialCode" suggestFields="materialCode" 
                            suggestUrl="${rc.getContextPath()}/manage/material/componentSuggest" lookupGroup="inventoryAlarmRecipientMaterialLookup"
                            remote="${rc.getContextPath()}/manage/material/validateMaterial"
                            warn="<@label key='materialCode.C,doesNotExist.C'>物料编号不存在</@label>"
                            </#if>
                            <#if pattern!="add">
                            readonly="readonly"
                            </#if>
                          />
                    </dd>
                </dl>
                <dl class="nowrap">
                    <dt>&nbsp;</dt>
                    <dd id="treeTypeCheck">
                        <label><input name="checkType" type="radio" tree="warehouseTree"
                        <#if pattern == "view" || pattern == "modify" && (hasWarehouse != '' ||  hasMaterialType != '')>
                            disabled="disabled"
                        </#if>
                        checked="checked" />仓库</label>
                        <label><input name="checkType" type="radio" tree="materialTypeTree"
                        <#if pattern == "view" || pattern == "modify" && (hasWarehouse != '' ||  hasMaterialType != '')>
                            disabled="disabled"
                        </#if>
                        <#if hasMaterialType == "true" && hasWarehouse == ''>
                            checked="checked"
                        </#if>
                        />物料类型</label>
                    </dd>
                </dl>
                <dl class="nowrap">
                    <dd style="width: 600px;" id="treeTypePanel">
                        <div id="warehouseTree" >
                            <ul class="tree treeCheck expand">
                                <li>
                                    <a>全选</a>
                                    <ul>
                                        <#list warehouseTrees as tree>
                                        <li type="warehouseType" lockFlag="${tree.lockFlag}"><a tvalue="${tree.nodeValue}" tname="warehouseType">${tree.nodeText}</a>
                                            <#if tree.children?? && tree.children?size gt 0>
                                            <ul>
                                                <#list tree.children as childTree>
                                                <#if (childTree.lockFlag != 1 && pattern == "add") || pattern != "add">
                                                <li type="warehouse" lockFlag="${childTree.lockFlag}"><a tvalue="${childTree.nodeValue}" tname="warehouse">${childTree.nodeText}</a>
                                                    <#if childTree.children?? && childTree.children?size gt 0>
                                                    <ul>
                                                        <#list childTree.children as grandsonTree>
                                                        <#if (grandsonTree.lockFlag != 1 && pattern == "add") || pattern != "add">
                                                        <li type="materialType" lockFlag="${grandsonTree.lockFlag}"><a tvalue="${childTree.nodeValue};${grandsonTree.nodeValue}" tname="warehouse_materialType">${grandsonTree.nodeText}</a></li>
                                                        </#if>
                                                        </#list>
                                                    </ul>
                                                    </#if>
                                                </li>
                                                </#if>
                                                </#list>
                                            </ul>
                                            </#if>
                                        </li>
                                        </#list>
                                    </ul>
                                </li>
                            </ul>
                        </div>
                        <div id="materialTypeTree" style="display: none;">
                            <ul class="tree treeCheck expand">
                                <li>
                                    <a>全选</a>
                                    <ul>
                                        <#list materialTypeTrees as tree>
                                        <#if (tree.lockFlag != 1 && pattern == "add") || pattern != "add">
                                        <li type="materialType" lockFlag="${tree.lockFlag}"><a tvalue="${tree.nodeValue}" tname="materialType">${tree.nodeText}</a></li>
                                        </#if>
                                        </#list>
                                    </ul>
                                </li>
                            </ul>
                        </div>
                    </dd>
                </dl>
                <dl class="nowrap">
                    <dt>&nbsp;</dt>
                    <dd>
                        <label><input type="checkbox" name="lockFlag" value="1"
                            <#if "view" == pattern>
                            disabled="disabled"
                            </#if>
                            <#if recipient.lockFlag == 1>
                            checked="true"</#if>><@label key="lock.C">锁定</@label></label>
                    </dd>
                </dl>
            </fieldset>
        </div>
        <div class="formBar">
            <ul>
                <#if pattern!="view">
                    <li>
                        <div class="buttonActive">
                            <div class="buttonContent">
                                <button id="saveInventoryAlarmRecipients" type="button"><@label key="save.B">保存</@label></button>
                            </div>
                        </div>
                    </li>
                    <li>
                        <div class="buttonActiveGrey">
                            <div class="buttonContent">
                                    <button type="button" class="close"><@label key="cancel.B">取消</@label></button>
                            </div>
                        </div>
                    </li>
                <#else>
                    <li>
                    <div class="buttonActive">
                        <div class="buttonContent">
                                <button type="button" class="close"><@label key="close.B">关闭</@label></button>
                        </div>
                    </div>
                </li>
                </#if>
            </ul>
        </div>
    </form>
</div>
<script>
(function($){
    
    $('#treeTypeCheck [type=radio]').on('change', function(){
        var id = '#' + $(this).attr('tree');
        $('#treeTypePanel > div').hide();
        if (this.checked) {
            $(id).show();
        }
    });
    
    
    var hasWarehouse = '${hasWarehouse}' || false, hasMaterialType = '${hasMaterialType}' || false,
    $page = $('#inventoryAlarmRecipientInfo'),
    $treeTypeCheck = $('#treeTypeCheck', $page),
    $treeTypePanel = $('#treeTypePanel', $page),
    $warehouseTree = $('#warehouseTree', $page),
    $materialTypeTree = $('#materialTypeTree', $page),
    $saveBtn = $('#saveInventoryAlarmRecipients', $page).on('click', function(event){
        if (!$('form', $page).valid()) {
            return false;
        }
        var selectedWarehouses = new Array(), 
        selectedWarehouseAndMaterialTypes = new Array(),
        selectedMaterialTypes = new Array(), 
        userCode = $('[name=userCode]', $page).val().trim(),
        storageLocationCode = $('[name=storageLocationCode]', $page).val().trim(),
        materialCode = $('[name=materialCode]', $page).val().trim(),
        lockFlag = $('[name=lockFlag]', $page)[0].checked ? 1 : 0;
        
        if ($('input:first', $treeTypeCheck)[0].checked) {
            $.each($('.selfchecked > input[name=warehouse]', $treeTypePanel), function(){
                selectedWarehouses.push(this.value);
            });
            // 仓库下没有物料类型的情况下，选中全选或者仓库类型时，仓库会成为选中状态
            $.each($('.checked > input[name=warehouse]', $treeTypePanel), function(){
                if ($('>ul>li', $(this).parents('li:first')).length == 0) {
                    selectedWarehouses.push(this.value);
                }
            });
            $.each($('.checked > input[name=warehouse_materialType]', $treeTypePanel), function(){
                selectedWarehouseAndMaterialTypes.push(this.value);
            });
        } else {
            $.each($('.checked > input[name=materialType]', $treeTypePanel), function(){
                selectedMaterialTypes.push(this.value);
            });
        }
        if (selectedWarehouses.length == 0 
                && selectedWarehouseAndMaterialTypes.length == 0
                && selectedMaterialTypes.length == 0 
                && storageLocationCode == ''
                && materialCode == '') {
            alertMsg.error('库位编号，物料编号，仓库及物料类型至少需要选填一项！');
            return false;
        }
        
        var postData = {
            navTabId: '${navTabId}',
            userCode: userCode,
            storageLocationCode: storageLocationCode,
            materialCode: materialCode,
            selectedWarehouses: selectedWarehouses.join(','),
            selectedWarehouseAndMaterialTypes: selectedWarehouseAndMaterialTypes.join(','),
            selectedMaterialTypes: selectedMaterialTypes.join(','),
            lockFlag: lockFlag,
            hasWarehouse: selectedWarehouses.length + selectedWarehouseAndMaterialTypes.length > 0,
            hasMaterialType: selectedMaterialTypes.length > 0
        };
        
        var checked = true;
        
        if ('${pattern}' == 'add') {
            $.DWZajax({
                url: '${rc.getContextPath()}/manage/inventoryAlarmRecipient/checkRecipients',
                data: postData,
                async: false,
                callback: function(data){
                    checked = (data.length == 0);
                }
            });
        }
        
        if ('${pattern}' == 'modify') {
            if (new Boolean(hasWarehouse) != postData.hasWarehouse 
                    || new Boolean(hasMaterialType)  != postData.hasMaterialType) {
                $.DWZajax({
                    url: '${rc.getContextPath()}/manage/inventoryAlarmRecipient/checkRecipients',
                    data: postData,
                    async: false,
                    callback: function(data){
                        checked = (data.length == 0);
                    }
                });
                postData.hasWarehouse = hasWarehouse;
                postData.hasMaterialType = hasMaterialType;
            }
        }
        
        if (!checked) {
            alertMsg.error('相同条件下的数据已经存在，操作失败！');
            return false;
        }
        
        $.DWZajax({
            url: '${rc.getContextPath()}/manage/inventoryAlarmRecipient/saveRecipients',
            data: postData,
            callback: dialogAjaxDone
        });
        
        var dialog = $page.parents('.dialog:first');
        $.pdialog.close(dialog);
    }),
    
    rClass= 'checked selfchecked unchecked indeterminate',
    
    _checkParent = function($ckbox) {
        var $node = $ckbox.parent().parent(), $tree = $node.parent();
        if ($tree.is('.tree')) return;
        
        var $parent = $tree.parent(), $parentCkbox = $('>div>div.ckbox', $parent),
        nodeLength = $('>li>a', $tree).length + $('div.ckbox', $tree).length,
        checkedLength = $('div.checked', $tree).length + $('div.selfchecked', $tree).length;
        
        if (nodeLength == checkedLength) {
            $parentCkbox.removeClass(rClass).addClass('checked');
        } else if (checkedLength == 0) {
            $parentCkbox.removeClass(rClass).addClass('unchecked');
        } else {
            $parentCkbox.removeClass(rClass).addClass('indeterminate');
        }
        
        if (checkedLength == 0) {
            $(':checkbox', $parentCkbox).removeAttr('checked');
        } else {
            $(':checkbox', $parentCkbox).attr('checked', true);
        }
        
        _checkParent($parentCkbox);
    },
    
    _checkChild = function($ckbox) {
        var $node = $ckbox.parent().parent(), $tree = $('>ul', $node);
        if ($tree.length == 0) return;
        $('>li>div>div.ckbox', $tree).each(function(){
            var $childCkbox = $(this);
            if ($ckbox.is('.checked')) {
                $childCkbox.removeClass(rClass).addClass('checked');
                $(':checkbox', $childCkbox).attr('checked', true);
            } else {
                $childCkbox.removeClass(rClass).addClass('unchecked');
                $(':checkbox', $childCkbox).removeAttr('checked');
            }
            _checkChild($childCkbox);
        });
    },
    // 针对编辑/查看详情，删除锁定状态，且没有被选中的节点
    _removeLockedNodes = function() {
        // 删除仓库下没有选中的锁定状态的物料类型的节点
        $('li[type=materialType][lockFlag=1]>div>.unchecked', $treeTypePanel).parent().parent().remove();
        // 删除锁定仓库下没有被选中的物料类型节点
        $('li[type=warehouse][lockFlag=1]>ul>li>div>.unchecked', $warehouseTree).parent().parent().remove();
        // 删除锁定状态且没有被选中的仓库节点
        $('li[type=warehouse][lockFlag=1]>div>.unchecked', $warehouseTree).parent().parent().remove();
        _removeInvalidTree();
    },
    // 更新树的节点状态，删除无用的节点
    _removeInvalidTree = function(){
        // 如果仓库下面没有物料类型，则改变树上展开/合并为node
        $.each($('li[type=warehouse]', $warehouseTree), function() {
            $this = $(this);
            if ($('>ul>li', $this).length == 0) {
                $('>div>.expandable', $this).removeAttr('class').addClass('node');
                $('>div>.collapsable', $this).removeAttr('class').addClass('node');
            }
        });
        // 如果仓库类型下面没有仓库，则移除仓库类型节点
        $.each($('li[type=warehouseType]', $warehouseTree), function(){
            var $this = $(this);
            if ($('>ul>li', $this).length == 0) {
                $this.remove();
            }
        });
        // 如果没有仓库类型节点，则删除根节点
        if ($('li[type=warehouseType]', $warehouseTree).length == 0) {
            $('#warehouseTree > ul').remove();
        }
        // 如果没有物料类型节点，则删除根节点
        if ($('li[type=materialType]', $materialTypeTree).length == 0) {
            $('#materialTypeTree > ul').remove();
        }
        // 最后需要重新改变各节点的选中状态
        $.each($('li[type=warehouse]', $warehouseTree), function() {
            $this = $(this);
            if ($('>ul>li', $this).length == 0) {
                _checkParent($('>div>.ckbox', $this));
            } else if ($('>div>.ckbox', $this).is(':not(.selfchecked)')) {
                _checkParent($('>ul>li:first>div>.ckbox', $this));
            }
        });
        if ($('li[type=materialType]:first>div>.ckbox', $materialTypeTree).length) {
            _checkParent($('li[type=materialType]:first>div>.ckbox', $materialTypeTree));
        }
    };
    
    if (hasMaterialType && !hasWarehouse) {
        $warehouseTree.hide();
        $materialTypeTree.show();
        $('input:first', $treeTypeCheck).parent().hide();
    } else if (hasWarehouse) {
        $('input:last', $treeTypeCheck).parent().hide();
    }
    
    $page.on('uiComplete', function(){
        var $tree = $('.tree', $warehouseTree);
        $('>li>ul>li>ul>li>ul', $tree).hide();
        $('>li>ul>li>ul>li>div>div:nth-child(3)', $tree).removeClass('collapsable').addClass('expandable');
        var $secondCkBoxs = $('>li>ul>li>ul>li>div>div.ckbox', $tree).off('click').on('click', function(){
            var $this = $(this), $li = $this.parent().parent();
            if ($this.is('.unchecked')) {
                $this.removeClass(rClass).addClass('selfchecked');
            } else if ($this.is('.checked') || ($this.is('.selfchecked') && $('>ul>li', $li).length == 0)) {
                // 如果是checked状态，或者是selfchecked状态而且没有子节点
                $this.removeClass(rClass).addClass('unchecked');
            } else {
                $this.removeClass(rClass).addClass('checked');
            }
            if ($this.is('.unchecked')) {
                $(':checkbox', $this).removeAttr('checked');
            } else {
                $(':checkbox', $this).attr('checked', true);
            }
            _checkChild($this);
            _checkParent($this);
        });
        var $thirdCkBoxs = $('>li>ul>li>ul>li>ul>li>div>div.ckbox', $tree).off('click').on('click', function(){
            var $this = $(this);
            if ($this.is('.checked')) {
                $this.removeClass('checked').addClass('unchecked');
            } else if ($this.is('.unchecked')) {
                $this.removeClass('unchecked').addClass('checked').parent().parent();
            }
            _checkParent($this);
        });
        
        _removeInvalidTree();
        
        if ('${userCode}') {
            $.DWZajax({
                url: '${rc.getContextPath()}/manage/inventoryAlarmRecipient/checkRecipients',
                data: {
                    navTabId: '${navTabId}',
                    userCode: '${userCode}',
                    storageLocationCode: '${storageLocationCode}',
                    materialCode: '${materialCode}',
                    hasWarehouse: '${hasWarehouse}' || false,
                    hasMaterialType: '${hasMaterialType}' || false
                },
                callback: function(data) {
                    $.each(data, function(){
                        var $ckBox;
                        if (this.warehouseCode && this.materialTypeCode) {
                            $ckBox = $('[type=checkbox][name=warehouse_materialType][value="' + this.warehouseCode + ';' + this.materialTypeCode + '"]', $tree).parent().addClass('checked');
                            $ckBox.parents('ul:first').show().parent().find('>div>.expandable').removeClass('expandable').addClass('collapsable');
                        } else if (this.warehouseCode) {
                            $ckBox = $('[type=checkbox][name=warehouse][value=' + this.warehouseCode + ']', $tree).parent().addClass('selfchecked');
                        } else if (this.materialTypeCode) {
                            $ckBox = $('[type=checkbox][name=materialType][value=' + this.materialTypeCode + ']', $('.tree', $materialTypeTree)).parent().addClass('checked');
                        }
                        if ($ckBox) {
                            _checkParent($ckBox.removeClass('unchecked'));
                        }
                    });
                    _removeLockedNodes();
                }
            });
        }
        // 详情页面禁用所有checkbox的click事件
        if ('${pattern}' == 'view') {
            $('.ckbox', $treeTypePanel).off('click');
        }
    });
    
})(jQuery);
</script>